import {
    getBlogDetails,
    getLeaveWordBlog,
    leaveWordlike,
    leaveWordUnlike,
    reportAudit,
    setBookingOrder,
    setCollectionBlog,
    setLeaveWordBlog,
    setLikeBlog,
    setSeeNumber,
    setUnCollectionBlog,
    setUnLikeBlog
} from "../../utils/api";
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

let iamgeList: any = [];
let lvList: any = ['https://www.lv666.top/IMG/1669704531107_lv1.png', 'https://www.lv666.top/IMG/1669704567334_lv2.png', 'https://www.lv666.top/IMG/1669704589511_lv3.png', 'https://www.lv666.top/IMG/1669704601622_lv4.png', 'https://www.lv666.top/IMG/1669704623408_lv5.png'];
let blogID: any;
let page = 1;
let number = 10;
let count = 0;
let index = 0;
let i = 0;
let baseURL = "http://192.168.0.101:3000";
let renderArr: any = [];
let renderImageArr: any = [];
let renderServeImageArr: any = [];
let contentMessage = "";
let leaveWordId = "";
let tempBlogId: any = "";
Page({
    data: {
        type: 1,
        imageUrlList: [],
        videoUrlList: [],
        renderObj: null,
        isLike: false,
        likeNumber: 0,
        valueLen: '0',
        value: '',
        isShowInputBox: false,
        topSide: 0,
        rectHeight: 0,
        isCollection: false,
        collrationNumber: 0,
        leaveWordNumber: 0,
        leaveWordArr: [],
        windowHeight: 0,
        reportState: false,
        renderImageArr: []
    },
    onLoad(event: any) {
        const BC = wx.getMenuButtonBoundingClientRect();
        const {windowHeight} = wx.getWindowInfo()
        this.setData({
            topSide: BC.top,
            rectHeight: BC.height,
            windowHeight
        })
        this.getBlogInfo(event.id);
        blogID = event.id;
        tempBlogId = blogID;
        setSeeNumber({
            blogId: event.id
        })
        page = 1;
        index = 0;
        i = 0;
        this.onGetBlogLeaveWord();
    },
    onLeaveWordReport(e: any) {
        this.setData({
            reportState: true
        })
        blogID = "";
        leaveWordId = e.currentTarget.dataset.id;
        // console.log(e.currentTarget.dataset.id)
    },
    // 上传举报
    onReport() {
        if (!contentMessage) {
            Toast.fail("还未写入举报原因");
            return
        }
        let obj: any = {};
        if (renderServeImageArr) {
            obj['imageUrl'] = JSON.stringify(renderServeImageArr);
        }
        if (blogID) {
            obj['blogId'] = blogID;
        }
        if (leaveWordId) {
            obj['leaveWordId'] = leaveWordId;
        }
        obj['content'] = contentMessage;
        reportAudit(obj).then(() => {
            Toast.success("举报成功")
        })
    },
    onInputMessage(e: any) {
        contentMessage = e.detail.value
    },
    // 删除图片
    deleteImage(e: any) {
        let arr: any = [];
        let serve: any = [];
        const i = e.detail.index;
        renderImageArr.forEach((val: any, index: any) => {
            if (index == i) {
                // delete renderServeImageArr[i]
            } else {
                arr.push(val);
                serve.push(renderServeImageArr[index])
            }
        })
        renderImageArr = arr;
        renderServeImageArr = serve;
        this.setData({
            renderImageArr: arr
        })
    },
    // 上传图片
    upLoadImage(url: any) {
        wx.uploadFile({
            url: `${baseURL}/api/file/uploadImage`,
            filePath: url,
            name: 'image',
            success: (res: any) => {
                let data = JSON.parse(res.data);
                renderServeImageArr.push({
                    thumb: data.data[0].thumbnail,
                    url: data.data[0].path,
                })
            }
        });
    },
    // 获取本地图片
    getImageURL(e: any) {
        e.detail.file.forEach((res: any, index: any) => {
            renderImageArr.push({url: res.url, isImage: true})
            this.upLoadImage(res.url)
            if (index + 1 == e.detail.file.length) {
                this.setData({
                    renderImageArr: renderImageArr
                })
            }
        })
    },
    // 显示举报界面
    onReportShow() {
        leaveWordId = "";
        blogID = tempBlogId;
        this.setData({
            reportState: true
        })
    },
    // 取消举报界面
    onReportClose() {
        this.setData({
            reportState: false
        })
    },
    // 点赞
    onClickLike(e: any) {
        const id = e.currentTarget.dataset.id;
        const is = e.currentTarget.dataset.is;

        if (is) {
            leaveWordUnlike({id})
            const arr = this.data.leaveWordArr;
            arr.forEach((res: any) => {
                if (res.id == id) {
                    res.isLike = !res.isLike;
                    res.likeNumber = +res.likeNumber - 1;
                }
            })
            this.setData({
                leaveWordArr: arr
            })
        } else {
            leaveWordlike({id})
            const arr = this.data.leaveWordArr;
            arr.forEach((res: any) => {
                if (res.id == id) {
                    res.isLike = !res.isLike;
                    res.likeNumber = +res.likeNumber + 1;
                }
            })
            this.setData({
                leaveWordArr: arr
            })
        }
    },
    // 取号
    onTakeNumber(e: any) {
        Dialog.confirm({
            title: '操作确认',
            message: '是否取号该服务',
        })
            .then(async () => {
                await setBookingOrder({
                    serviceItemsID: e.currentTarget.dataset.serviceid,
                    hairstylistID: e.currentTarget.dataset.hairid
                });
                const toast: any = Toast.loading({
                    duration: 0, // 持续展示 toast
                    forbidClick: true,
                    message: '取号成功 3 秒后进入订单页',
                    selector: '#custom-selector',
                });
                let second = 3;
                const timer = setInterval(() => {
                    second--;
                    if (second) {
                        toast.setData({
                            message: `取号成功 ${second} 秒后进入订单页`,
                        });
                    } else {
                        clearInterval(timer);
                        Toast.clear();
                        wx.switchTab({
                            url: "../order/order"
                        })
                    }
                }, 1000);
            })
    },
    // 获取留言
    async onGetBlogLeaveWord() {
        const res = await getLeaveWordBlog({blogID, page, number});
        renderArr = res.rows;
        count = res.count;
        this.onListRenderBegin();
    },
    // 渲染留言开始
    onListRenderBegin() {
        if (!renderArr[i]) {
            i = 0;
            renderArr = [];
            return;
        }
        this.onListRenderAfter();
    },
    // 渲染留言之后
    onListRenderAfter() {
        this.setData({
            ["leaveWordArr[" + index + "]"]: renderArr[i]
        }, () => {
            index++;
            i++;
            this.onListRenderBegin()
        })
    },
    // 跳转预约页面
    onAppointment(e: any) {
        console.log(e['currentTarget']['dataset'])
        wx.navigateTo({
            url: `../subscribe/subscribe?id=${e.currentTarget.dataset.serviceid}&hairstylist=${e['currentTarget']['dataset']['hairid']}&blogId=${e['currentTarget']['dataset']['blogid']}`
        })
    },
    // 跳转店铺
    onBreakShopDetailsPage(e: any) {
        const id = e.currentTarget.dataset.shopid;
        wx.navigateTo({
            url: `../shopDetails/shopDetails?id=${id}`
        })
    },
    onReturnPage() {
        wx.navigateBack({
            delta: 1
        })
    },
    async getBlogInfo(id: any) {
        const res = await getBlogDetails({id, random: Math.random()})
        if (res.userBasicInfo_tb.credibility >= 0 && res.userBasicInfo_tb.credibility < 100) {
            res.userBasicInfo_tb.credibility = lvList[0];
        } else if (res.userBasicInfo_tb.credibility >= 100 && res.userBasicInfo_tb.credibility < 200) {
            res.userBasicInfo_tb.credibility = lvList[1];
        } else if (res.userBasicInfo_tb.credibility >= 200 && res.userBasicInfo_tb.credibility < 300) {
            res.userBasicInfo_tb.credibility = lvList[2];
        } else if (res.userBasicInfo_tb.credibility >= 300 && res.userBasicInfo_tb.credibility < 400) {
            res.userBasicInfo_tb.credibility = lvList[3];
        } else {
            res.userBasicInfo_tb.credibility = lvList[4];
        }

        this.setData({
            type: res.type,
            imageUrlList: res.imageUrl,
            videoUrlList: res.videoUrl,
            renderObj: res,
            isLike: res.isLike,
            likeNumber: res.likeNumber,
            isCollection: res.isCollration,
            collrationNumber: res.collectionNumber,
            leaveWordNumber: res.leaveWordNumber
        })
        if (res.imageUrl) {
            iamgeList = [];
            res.imageUrl.forEach((element: any) => {
                iamgeList.push(element.url)
            });
        }
    },
    onViewLargerPictureFn(e: any) {
        const url = e.currentTarget.dataset.url;
        wx.previewImage({
            current: url,
            urls: iamgeList
        })
    },
    onInputValue(e: any) {
        this.setData({
            valueLen: e.detail.cursor,
            value: e.detail.value
        })
    },
    onReset() {
        this.setData({
            value: "",
            valueLen: '0'
        })
    },
    // 上传留言
    async onUploadMessage() {
        const res = await setLeaveWordBlog({
            messageContent: this.data.value,
            blogID
        })
        if (res.flag) {
            index = 0;
            i = 0;
            page = 1;
            Toast('🙂发表成功了🙂');
            this.onGetBlogLeaveWord();
            this.onReset();
            this.setData({
                leaveWordNumber: this.data.leaveWordNumber + 1,
                isShowInputBox: false
            })
        }
    },
    // 切换留言状态
    onChangeShowInputBoxState() {
        this.setData({
            isShowInputBox: !this.data.isShowInputBox
        })
    },
    // 点我喜欢
    async onLikeFn() {
        let state = this.data.isLike;
        if (!state) {
            const res = await setLikeBlog({blogID})
            if (res.flag) {
                this.setData({
                    isLike: true,
                    likeNumber: this.data.likeNumber + 1
                })
            }
        } else {
            const res = await setUnLikeBlog({blogID})
            if (res.flag) {
                this.setData({
                    isLike: false,
                    likeNumber: this.data.likeNumber - 1
                })
            }
        }
    },
    // 点我收藏
    async onCollection() {
        let state = this.data.isCollection;
        if (!state) {
            const res = await setCollectionBlog({blogID})
            if (res.flag) {
                this.setData({
                    isCollection: true,
                    collrationNumber: this.data.collrationNumber + 1
                })
            }
        } else {
            const res = await setUnCollectionBlog({blogID})
            if (res.flag) {
                this.setData({
                    isCollection: false,
                    collrationNumber: this.data.collrationNumber - 1
                })
            }
        }
    },
    // 触底加载
    async onScrollTolower() {
        if (page * number >= count) {
            Toast('🙂到底了哦~~🙂');
            return;
        }
        page++;
        const res = await getLeaveWordBlog({page, number, blogID});
        renderArr = res.rows;
        count = res.count;
        this.onListRenderBegin();
    }
})